package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.utils.UUIDUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@Namespace("/")
@ParentPackage("struts-default")
@Scope("prototype")
@Controller
public class PromotionAction extends BaseAction<Promotion> {
	private static final long serialVersionUID = 1L;
	@Autowired
	private PromotionService promotionService;
	// 接受图片文件
	// 图片上传
	private File titleImgFile;
	private String titleImgFileFileName;

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	@Action(value = "promotion_save", results = {
			@Result(name = "success", location = "./pages/take_delivery/promotion.html", type = "redirect") })
	public String save() throws IOException {
		// 保存的磁盘路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload");
		// 保存的服务器路径
		String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload";
		// 修改上传的文件名
		String randomFileName = UUIDUtils.getUUID() + titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		// 保存文件到磁盘
		FileUtils.copyFile(titleImgFile, new File(savePath, randomFileName));
		// 设置模型中的titleImg属性
		model.setTitleImg(saveUrl+"/"+randomFileName);
		//调用业务层保存数据
		promotionService.save(model);
		return SUCCESS;
	}
	
	//分页查找所有
	@Action(value="promotion_pageQuery")
	public void pageQuery() throws Exception{
		Pageable pageable = new PageRequest(page-1, rows);
		Page<Promotion> pageData = promotionService.findAll(pageable);
		pageDataJsonToWeb(pageData);
	}
	
}
